package com.dongdongshop.config;

import com.dongdongshop.shiro.LoginShiro;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(){

        //创建 ShiroFilterFactoryBean 对象 --- shiro的过滤器
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        //设置 DefaultWebSecurityManager 安全管理器
        shiroFilterFactoryBean.setSecurityManager(getDefaultWebSecurityManager());

        //配置shiro的内置过滤器
        Map<String, String> filterMap = new LinkedHashMap<>();  //LinkedHashMap 能够保证数据存取顺序一致
        /*
         *  anon : 不需要登录就能访问
         *  authc : 必须登录才能访问
         *  perms : 登陆后也不行, 需要设置权限后才能访问
         *  login : 退出登录
         * */
        // key 为访问路径, value 为过滤级别
        //放过
        filterMap.put("/**/*.js", "anon");
        filterMap.put("/**/*.css", "anon");
        filterMap.put("/**/*.png", "anon");
        filterMap.put("/**/*.jpg", "anon");

        filterMap.put("/loginController/toLogin", "anon");
        filterMap.put("/loginController/login", "anon");


        //退出用户
        filterMap.put("/loginController/outLogin", "logout");
        //登录过滤
        filterMap.put("/**", "authc");

        // 自定义登录页面
        shiroFilterFactoryBean.setLoginUrl("/loginController/toLogin");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        return shiroFilterFactoryBean;
    }


    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(){

        //创建 DefaultWebSecurityManager 安全管理器对象 --- 用来管理用户主体的subject
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();

        //关联自定义的 Realm
        defaultWebSecurityManager.setRealm(getUserRealm());

        return defaultWebSecurityManager;
    }

    //创建 Realm 实例对象
    @Bean
    public LoginShiro getUserRealm(){
        LoginShiro loginShiro = new LoginShiro();
        //设置加密方式
//        loginShiro.setCredentialsMatcher(hashedCredentialsMatcher());
        return loginShiro;
    }

//    //配置加密方式
//    @Bean
//    public HashedCredentialsMatcher hashedCredentialsMatcher(){
//        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
//        //指定加密方式
//        hashedCredentialsMatcher.setHashAlgorithmName("MD5");   //散列算法: MD4, MD5, SHA-1, SHA-256, SHA-384, SHA-512等
//        System.out.println("加密方式: MD5");
//        //指定加密次数
//        hashedCredentialsMatcher.setHashIterations(1);  //撒盐次数
//        // true加密用hex编码, false用base64编码
//        hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true);
//        return hashedCredentialsMatcher;
//    }
}
